package timing.ukulele.auth.security.type.wechat;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import timing.ukulele.auth.security.ThirdTypeEnum;
import timing.ukulele.auth.security.user.TimingUserDetailService;

public class ThirdQrAuthenticationProvider implements AuthenticationProvider {

    private TimingUserDetailService userService;

    public TimingUserDetailService getUserService() {
        return userService;
    }

    public void setUserService(TimingUserDetailService myUserService) {
        this.userService = myUserService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        ThirdQrAuthenticationToken authenticationToken = (ThirdQrAuthenticationToken) authentication;
        ThirdTypeEnum thirdType = authenticationToken.getThirdType();
        UserDetails user = userService.loadUserByThirdOpenCode((String) authenticationToken.getPrincipal(), thirdType.getCode());
        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        ThirdQrAuthenticationToken result = new ThirdQrAuthenticationToken(user, user.getAuthorities());
        result.setDetails(authenticationToken.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return ThirdQrAuthenticationToken.class.isAssignableFrom(aClass);
    }
}